//download组件，按照队列依次下载，若有优先下载的内容，则优先下载
function Downloads(){
  //待下载的文件数
  this.fileNum = 0;
  //下载文件列表 priority 为优先级，1为优先级最高，按照优先级依次下载（并发不超过10）
  this.files = [];
  //优先下载列表 将优先级设置为0的下载任务放置到该列表，该列表完成后，会执行一个回调方法 callbackMust
  this.priorityFiles = [];
  //优先下载文件已下载数量
  this.downPriorityNum = 0;
  //普通下载文件已下载数量
  this.downFileNum = 0;
  //当前下载数
  this.currentDown = 0;
}


//添加下载文件，file属性为：priority优先级；downUrl:下载链接；fileName:回调赋值属性名
Downloads.prototype.addFile = function (priority, downUrl, fileName) {
  let file = {
    priority: priority,
    downUrl: downUrl,
    fileName: fileName
  }
  this.fileNum = this.fileNum + 1;
  if (file.priority == 0) {
    this.priorityFiles.push(file);
  } else {
    this.files.push(file);
  }
}

//添加下载文件，file属性为：priority优先级；downUrl:下载链接；fileName:回调赋值属性名
Downloads.prototype.addFiles = function(file){
  this.fileNum = this.fileNum+1;
  if(file.priority == 0){
    this.priorityFiles.push(file);
  }else{
    this.files.push(file);
  }
}

/**
 * [开始下载功能] 优先下载priorityFiles列表，下载完成后回调callbackMust，所有任务下载完成后，回调callback
 * @param  {Function} callback     [所有任务下载完成后回调方法]
 * @param  {[type]}   callbackMust [优先级为0的任务下载完成后回调方法]
 * @return {[type]}                [description]
 */
Downloads.prototype.startup = function(callback,callbackMust){
  this.downFiles();
  this.backMethod(callback);
  this.backMust(callbackMust);
}

/**
 * [callback方法，settimeout监测回调时机]
 * @param  {Function} callback     [全部下载完成回调]
 * @return {[type]}                [description]
 */
Downloads.prototype.backMethod = function(callback){
  let that = this;
  //若文件未下载完成，每500ms检查一次是否符合回调状态
  if((this.downPriorityNum + this.downFileNum) < this.fileNum){    
    setTimeout(function(){
      that.backMethod(callback);
    },500)
  }
  else if(typeof(this.notifyMethod) == 'undefined' ||!this.notifyMethod){
    that.notifyMethod = true;
    callback(this.files);
  }  
}
/**
 * [callback方法，settimeout监测回调时机]
 * @param  {[type]}   callbackMust [优先级为0的任务下载完成后回调方法]
 * @return {[type]}                [description]
 */
Downloads.prototype.backMust = function(callbackMust){
  let that = this;
  //若文件未下载完成，每500ms检查一次是否符合回调状态
  if(this.downPriorityNum<this.priorityFiles.length){
    setTimeout(function(){
      that.backMust(callbackMust);
    },500)
  }
  else if(typeof(this.notifyMust) == 'undefined' ||!this.notifyMust){
    console.log("backMust is " + new Date());
    that.notifyMust = true;
    callbackMust(this.priorityFiles);   
  }  
}


/**
 * [下载单个文件，若并发数>9则等待500ms]
 * @param  {[file]} file [下载文件]
 * @param  {[boolean]} flag [是否为优先下载，true为是，false为否]
 * @return {[type]}      [description]
 */
Downloads.prototype.downFiles = function(file,flag){
  let that = this;  
  //若并发数达到10个，则等待500ms
  if(this.currentDown>9){
    setTimeout(function(){
      that.downFiles();
    },500)
  }else{
    if(typeof(file)!='undefined'&&file!=null){
      file.isDownload = true;
      this.currentDown++;
      wx.downloadFile({
        url: file.downUrl,
        success: function (res) {
          file.resUrl = res.tempFilePath;
          if(flag){
            that.downPriorityNum++;
          }else{
            that.downFileNum++;
          }
          that.currentDown--;
        }
      })
    }

    //优先下载priorityFiles
    if(this.priorityFiles.length>0){
      for(let i = 0;i<this.priorityFiles.length;i++){
        if(typeof(this.priorityFiles[i].isDownload) == 'undefined'){
          that.downFiles(this.priorityFiles[i],true);
        }
      }
    }
    //下载文件版本
    if(this.files.length>0){
      for(let i = 0;i<this.files.length;i++){
        if(typeof(this.files[i].isDownload) == 'undefined'){
          that.downFiles(this.files[i],false);
        }
      }
    }

  }
}

module.exports = Downloads;